package com.lgmshare.component.app;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import androidx.annotation.LayoutRes;
import androidx.annotation.MenuRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.lgmshare.component.logger.Logger;
import com.lgmshare.component.utils.PermissionCheckUtils;
import com.lgmshare.component.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * activity基类,集成权限请求
 *
 * @author: lim
 * @version: V1.0
 * @description: 基础activity
 * @datetime: 2014-6-3 10:14
 * @email: lgmshare@gmail.com
 */
public abstract class LaraActivity extends AppCompatActivity {

    protected final String TAG = LaraActivity.this.getClass().getName();

    /** 集成权限处理*/
    // 系统权限管理页面的参数
    private static final int PERMISSION_REQUEST_CODE = 0x123;
    private PermissionCheckCallback mPermissionCheckCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.v(TAG, "onCreate");

        initData();
        if (isFinishing()) {
            return;
        }
        //页面内容可能取决于相关数据
        int resId = onBindLayoutResId();
        if (resId > 0) {
            setContentView(onBindLayoutResId());
        }
        initView();
        if (isFinishing()) {
            return;
        }
        initLoad();
    }

    /**
     * 绑定布局资源文件ID
     * use with {@link #onCreate(Bundle)}
     *
     * @return 资源布局文件ID
     */
    protected abstract @LayoutRes
    int onBindLayoutResId();

    /**
     * 初始化Intent Data
     * use with {@link #onCreate(Bundle)}
     */
    protected abstract void initData();

    /**
     * 初始化界面View
     * <p/>
     * use with {@link #onCreate(Bundle)}
     */
    protected abstract void initView();

    /**
     * 初始化数据加载
     * use with {@link #onCreate(Bundle)}
     */
    protected abstract void initLoad();

    /**
     * @return menu
     */
    protected @MenuRes
    int onBindMenuResId() {
        return 0;
    }

    /**
     * {@code getMenuInflater().inflate(menu(), menu);}之后调用
     *
     * @param menu
     */
    protected void initMenus(Menu menu) {
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (onBindMenuResId() != 0) {
            getMenuInflater().inflate(onBindMenuResId(), menu);
        }
        initMenus(menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            hideInputMethod();
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Logger.v(TAG, "onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Logger.v(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        hideInputMethod();
        Logger.v(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Logger.v(TAG, "onStop");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Logger.v(TAG, "onDestroy");
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        Logger.v(TAG, "onUserInteraction");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Logger.v(TAG, "onSaveInstanceState");
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Logger.v(TAG, "onRestoreInstanceState");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Logger.v(TAG, "onRestart");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        Logger.v(TAG, "onBackPressed");
    }

    @Override
    public void finish() {
        super.finish();
        Logger.v(TAG, "activity finish");
    }

    /**
     * 获取activity
     *
     * @return
     */
    protected Activity getActivity() {
        return this;
    }

    protected void hideInputMethod() {
        UIUtils.hideInputMethod(this);
    }

    /**
     * 检查功能权限
     *
     * @param permission
     * @return
     */
    protected boolean checkPermission(String permission) {
        return checkPermission(new String[]{permission});
    }

    /**
     * 检查功能权限
     *
     * @param permissions
     * @return
     */
    protected boolean checkPermission(String[] permissions) {
        return PermissionCheckUtils.checkPermission(this, permissions);
    }

    /**
     * 启动当前权限页面的公开接口
     * targetSdkVersion必须在 >=23，才能返回正确的操作值
     *
     * @param permission         权限
     * @param permissionCallback 权限结果回调
     */
    protected void checkRequestPermission(String permission, PermissionCheckCallback permissionCallback) {
        checkRequestPermission(new String[]{permission}, permissionCallback);
    }

    /**
     * 启动当前权限页面的公开接口
     * targetSdkVersion必须在 >=23，才能返回正确的操作值
     *
     * @param permissions        权限组
     * @param permissionCallback 权限结果回调
     */
    protected void checkRequestPermission(String[] permissions, PermissionCheckCallback permissionCallback) {
        //检测权限
        boolean result = PermissionCheckUtils.checkPermission(this, permissions);
        if (result) {
            if (permissionCallback != null) {
                permissionCallback.onPermissionsGranted(permissions);
            }
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                mPermissionCheckCallback = permissionCallback;
                PermissionCheckUtils.requestPermissions(this, permissions, PERMISSION_REQUEST_CODE);
            } else {
                if (permissionCallback != null) {
                    permissionCallback.onPermissionsGranted(permissions);
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            List<String> grantedList = new ArrayList<>();
            List<String> deniedList = new ArrayList<>();
            for (int i = 0; i < permissions.length; i++) {
                String permission = permissions[i];
                if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                    grantedList.add(permission);
                } else {
                    deniedList.add(permission);
                }
            }
            if (permissions.length == grantedList.size()) {
                //已授权
                if (mPermissionCheckCallback != null) {
                    String[] strings = grantedList.toArray(new String[grantedList.size()]);
                    mPermissionCheckCallback.onPermissionsGranted(strings);
                    mPermissionCheckCallback = null;
                }
            } else {
                //未授权
                if (mPermissionCheckCallback != null) {
                    String[] strings = deniedList.toArray(new String[deniedList.size()]);
                    mPermissionCheckCallback.onPermissionDenied(strings);
                    mPermissionCheckCallback = null;
                }
            }
        }
    }

    /**
     * 权限回调
     */
    public interface PermissionCheckCallback {

        void onPermissionsGranted(String[] permissions);

        void onPermissionDenied(String[] permissions);
    }
}
